package app.aptech.translate;

import java.io.File;

import com.googlecode.tesseract.android.TessBaseAPI;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import app.aptech.translate.R;

public class MainActivity extends FragmentActivity {
	protected static final String TAG = "photo_taken";
	public static Context appContext;
	private LinearLayout slidingPanel;
	private boolean isExpanded;
	private DisplayMetrics metrics;
	private RelativeLayout headerPanel;
	private RelativeLayout menuPanel;
	private int panelWidth;
	private ImageView menuViewButton;
	private String selectedImagePath;
	private String fileName;
	Button ButtonClick;
	int CAMERA_PIC_REQUEST = 1337;
	public int TAKE_PICTURE = 2;
	public int GET_PICTURE = 1;
	public int ORC_PICTURE = 3;
	ImageView editpic;
	TextView txtSelected;
	Button btnTranslate;
	TextView menuClick;
	Spinner sp;
	final Context context = this;
	FrameLayout.LayoutParams menuPanelParameters;
	FrameLayout.LayoutParams slidingPanelParameters;
	LinearLayout.LayoutParams headerPanelParameters;
	LinearLayout.LayoutParams listViewParameters;
	protected int REQUEST_CODE;
	EditText langCodeField;

	public static final String PACKAGE_NAME = "app.aptech.translate";
	public static final String DATA_PATH = Environment
			.getExternalStorageDirectory().toString() + "/ImageTranslator/";
	public static final String lang = "vie";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_one);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		txtSelected = (TextView) findViewById(R.id.txtSelected);
		btnTranslate = (Button) findViewById(R.id.btnTranslate);
		sp = (Spinner) findViewById(R.id.spinner1);
		sp.setVisibility(View.INVISIBLE);
		txtSelected.setVisibility(View.INVISIBLE);
		btnTranslate.setVisibility(View.INVISIBLE);

		// editpic = (ImageView) findViewById(R.id.imgView);
		selectedImagePath = Environment.getExternalStorageDirectory()
				+ "/images/make_machine_example.jpg";
		// Initialize
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		panelWidth = (int) ((metrics.widthPixels) * 0.75);
		headerPanel = (RelativeLayout) findViewById(R.id.header2);
		headerPanelParameters = (LinearLayout.LayoutParams) headerPanel
				.getLayoutParams();
		headerPanelParameters.width = metrics.widthPixels;
		headerPanel.setLayoutParams(headerPanelParameters);
		menuPanel = (RelativeLayout) findViewById(R.id.menuPanel);
		menuPanelParameters = (FrameLayout.LayoutParams) menuPanel
				.getLayoutParams();
		menuPanelParameters.width = panelWidth;
		menuPanel.setLayoutParams(menuPanelParameters);
		slidingPanel = (LinearLayout) findViewById(R.id.slidingPanel);
		slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel
				.getLayoutParams();
		slidingPanelParameters.width = metrics.widthPixels;
		slidingPanel.setLayoutParams(slidingPanelParameters);

		// menu
		menuClick = (TextView) findViewById(R.id.menu_item_2);
		menuClick.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				System.exit(0);
			}
		});
		// menu
		menuClick = (TextView) findViewById(R.id.menu_item_1);
		menuClick.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						InfoActivity.class);
				MainActivity.this.startActivity(intent);
			}
		});
		// camera
		ButtonClick = (Button) findViewById(R.id.buttonCamera);
		ButtonClick.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// Log.v(TAG, "Starting Camera app");
				takeImage();
			}
		});
		// gallery
		ButtonClick = (Button) findViewById(R.id.btnGallery);
		ButtonClick.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// Log.v(TAG, "Starting gallery app");
				openImage();
			}
		});
		// translate
		ButtonClick = (Button) findViewById(R.id.btnTranslate);
		ButtonClick.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
				TessBaseAPI baseApi = new TessBaseAPI();
				baseApi.setDebug(true);
				baseApi.init(DATA_PATH, lang);
				baseApi.setImage(bitmap);
				String recognizedText = baseApi.getUTF8Text();
				baseApi.end();
				Log.v(TAG, "OCRED TEXT: " + recognizedText);

				if (lang.equalsIgnoreCase("vie")) {
					recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+",
							" ");
				}

				recognizedText = recognizedText.trim();

				if (recognizedText.length() != 0) {
					AlertDialog.Builder dialog= new AlertDialog.Builder(context);
					dialog.setTitle("Result");
					dialog.setMessage(recognizedText						
							);
					
				}
			}
		});
		ButtonClick.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					// Button Pressed
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					// finger was lifted
				}
				return false;
			}
		});
		// menu
		menuViewButton = (ImageView) findViewById(R.id.menuViewButton);
		menuViewButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!isExpanded) {
					isExpanded = true;

					// Expand
					new ExpandAnimation(slidingPanel, panelWidth,
							Animation.RELATIVE_TO_SELF, 0.0f,
							Animation.RELATIVE_TO_SELF, 0.75f, 0, 0.0f, 0, 0.0f);
				} else {
					isExpanded = false;

					// Collapse
					new CollapseAnimation(slidingPanel, panelWidth,
							TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
							TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
							0, 0.0f);
				}
			}
		});
	}

	protected void takeImage() {
		File file = new File(selectedImagePath);
		Uri outputFileUri = Uri.fromFile(file);
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PICTURE);
	}

	protected void openImage() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				GET_PICTURE);
	}

	protected void tranImage() {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

		switch (requestCode) {
		case 1:
			if (resultCode == RESULT_OK) {
				editpic = (ImageView) findViewById(R.id.imgView);
				Uri selectedImageUri = imageReturnedIntent.getData();
				editpic.setImageURI(selectedImageUri);
				txtSelected.setVisibility(View.VISIBLE);
				btnTranslate.setVisibility(View.VISIBLE);
				fileName = getPath(imageReturnedIntent.getData());
				txtSelected.setText("File: "
						+ getStringNameFromRealPath(fileName));
				Toast.makeText(this, "Import sucessful!", Toast.LENGTH_LONG)
						.show();
				break;
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Cancel import", Toast.LENGTH_LONG).show();
			}
		case 2:
			if (resultCode == RESULT_OK) {
				editpic = (ImageView) findViewById(R.id.imgView);
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 4;
				Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,
						options);
				editpic.setImageBitmap(bitmap);

				btnTranslate.setVisibility(View.VISIBLE);
				Toast.makeText(this, "Import image sucessfull",
						Toast.LENGTH_LONG).show();
				break;
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Cancel import", Toast.LENGTH_LONG).show();
			}
		case 3:
			if (resultCode == RESULT_OK) {

			}
		}
	}

	private String getStringNameFromRealPath(final String bucketName) {
		return bucketName.lastIndexOf('/') > 0 ? bucketName
				.substring(bucketName.lastIndexOf('/') + 1) : bucketName;
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

}